<?php

namespace Admin\Controller;

class GoodsController extends AdminController {

    public function index() {
        $keywords = I('keywords');
        if ($keywords) {
            $map['g.goods_id'] = array('like', "%{$keywords}%");
            $map['g.goods_name'] = array('like', "%{$keywords}%");

            $map['_logic'] = 'or';
            $where['_complex'] = $map;
            $this->assign('keywords', $keywords);
        }

        $cate_id = I('cate_id', 0, 'intval');

        $where['g.is_del'] = 0;
        if ($cate_id != 0) {
            $where['g.cate_id'] = $cate_id;
            $this->assign('cate_id', $cate_id);
        }

        $center_id = I('center_id', 0, 'intval');

        if ($center_id != 0) {
            $where['g.center_id'] = $center_id;
            $this->assign('center_id', $center_id);
        }

        $M = M()->table("ot_goods g")
                ->join('left join ot_center c on g.center_id =c.center_id')
                ->join('left join ot_goods_cate gc on g.cate_id =gc.cate_id');

        $field = 'g.*,gc.title,c.center_name';

        $order = "g.goods_id desc";
        $list = $this->lists($M, $where, $order, $field);

        if (!empty($list)) {
            foreach ($list as &$val) {
                $val['user_collect_num'] = M('Collect')->where(['goods_id' => $val['goods_id']])->count();
                $cate_title  = M('GoodsCate')->where(['cate_id'=>array('in',$val['cate_id'])])->getField('title', TRUE);
                $val['title'] = implode(',', $cate_title);
            }
            unset($val);
        }

        $menus = M('GoodsCate')->field(true)->select();
        $menus = D('Common/Tree')->toFormatTree($menus, 'title', 'cate_id');
        $menus = array_merge(array(0 => array('cate_id' => 0, 'title_show' => '顶级分类')), $menus);

        $center = M('Center')->order('sort')->select();

        $this->assign('center', $center);
        $this->assign('Menus', $menus);
        $this->assign('_list', $list);
        $this->display();
    }

    public function add() {
        $id = I("id", 0, 'intval');

        if (IS_POST) {
            $img = I('image_list');
//            $barcode = I('qcode');
            $data['goods_name'] = I("goods_name");
            $data['cate_id'] = I("cate_id");


            $data['explain'] = I("explain");
//            $data['qcode'] = implode(',', $barcode);
            $data['head_img'] = I("head_img");
            $data['goods_pic'] = implode(',', $img);
            $data['price'] = I("price", 0);
            $data['center_id'] = ','.implode(',', I("center_id")).',';

//            $data['collect_num'] = I('collect_num', 0, 'intval');


            if (empty($data['cate_id'])) {
                $this->error('请选择商品分类!');
            }

            $data['cate_id'] = ','.implode(',', I("cate_id")).',';

            if (empty($data['goods_name'])) {
                $this->error('请填写商品标题!');
            }

            if (empty($data['head_img'])) {
                $this->error('请选择商品主图!');
            }

            $data['update_time'] = date('Y-m-d H:i:s', time());

            if ($id == 0) {
                $trans = M();
                $trans->startTrans(); //开启事务
                try {
                    $data['explain'] = '<p style="font-weight:bold;font-size:15px;">自我介绍:</p>' . $data['explain'];
                    $res = M('Goods')->add($data);
                    $trans->commit();
                } catch (Exception $ex) {
                    $trans->rollback();
                    $this->error('操作失败');
                }
            } else {
                $trans = M();
                $trans->startTrans(); //开启事务
                try {
                    $res = M('Goods')->where(array('goods_id' => $id))->save($data);

                    $trans->commit();
                } catch (Exception $ex) {
                    $trans->rollback();
                    $this->error('操作失败');
                }
            }

            $this->success('操作成功', U('index'));
        } else {

            $data = M('Goods')->where(array("goods_id" => $id))->find();

            if ($data) {

                if (!empty($data['cate_id'])) {
                    $data['cate_id'] = explode(',', $data['cate_id']);
                }
                
                if (!empty($data['center_id'])) {
                    $data['center_id'] = explode(',', $data['center_id']);
                }
                if (!empty($data['goods_pic'])) {
                    $data['image_list'] = explode(',', $data['goods_pic']);
                }

//                if (!empty($data['qcode'])) {
//                    $data['qcode'] = explode(',', $data['qcode']);
//                }
                $data['img_count'] = count($data['image_list']);
            }

            $this->assign('data', $data);
//            $slist = M('GoodsCate')->field('cate_id,title')->select();

            $menus = M('GoodsCate')->field(true)->select();
            $menus = D('Common/Tree')->toFormatTree($menus, 'title', 'cate_id');
            $menus = array_merge(array(0 => array('cate_id' => 0, 'title_show' => '顶级分类')), $menus);
            $this->assign('clist', $menus);
            $list = array();

//            var_dump($list);die;
            $this->assign('gs_list', $list);

            $center = M('Center')->where(['type' => 0])->order('sort')->select();
            $this->assign('center', $center);
            $this->display();
        }
    }

    //规格列表
    public function specList() {
        $where = '1=1';
        $cate_id = I('cate_id', 0, 'intval');
        if ($cate_id) {
            $where .= ' AND s.cate_id=' . $cate_id;
        }
        $M = M()->table("ot_spec s")
                ->join("ot_cate_all as ca ON s.cate_id = ca.cate_id");

        $field = 's.*,ca.cate_name';
        $order = "s.spec_id ASC";
        $list = $this->lists($M, $where, $order, $field);
        if (!empty($list)) {
            $SpecSon = M('spec_son');
            foreach ($list as &$val) {
                $val['spec_group'] = '';
                $specSonList = $SpecSon->field('spec_son_id,spec_son_name,spec_id')->where(array('spec_id' => $val['spec_id'], 'is_del' => 0))->select();
                if (!empty($specSonList)) {
                    $val['spec_group'] = $specSonList;
                }
            }
        }
        $this->assign('_list', $list);
    }

    //规格项组合
    public function specSonCombination() {
        $data = $_POST['data'];
        $goods_id = I('goods_id', 0, 'intval');
        if (empty($data)) {
            $this->error('请选择规格');
        }
        $is_pass = 0;   //不能通过
        foreach ($data as $key => $val) {
            if (!empty($val)) {
                $is_pass = 1;
                $specSonIds[] = $val;
                $spec_ids[] = $key;
            }
        }

        if ($is_pass == 0) {
            $this->error('请选择规格。');
        }
        $specSonList = M()->table('ot_spec_son ss')->field('ss.*,s.spec_name')
                ->join('ot_spec as s ON s.spec_id = ss.spec_id')
                ->where(array('ss.spec_id' => array('in', $spec_ids)))
                ->select();
        if ($specSonList) {
            foreach ($specSonList as $val) {
                $newSpecSon[$val['spec_son_id']] = $val;
            }
        }
        $result = combinationList($specSonIds);
        if ($result) {
            $arrResultList = array();
            foreach ($result as $key => $val) {
                $son_id = ',';
                $item = array();
                $spec_title = '';
                foreach ($val as $kk => $vv) {
                    $son_id .= $vv . ',';
                    $item['spec_son_name'][] = $newSpecSon[$vv]['spec_son_name'];
                    $spec_title = $spec_title . $newSpecSon[$vv]['spec_name'] . ":" . $newSpecSon[$vv]['spec_son_name'] . " ";
                }
                $item['spec_title'] = $spec_title;
                $item['attr_id'] = $son_id;

                //判断是否已经添加过该规格组合
                if ($goods_id != 0) {
                    $gs_info = M('GoodsSon')->where(array('goods_id' => $goods_id, 'spec_group' => $son_id, 'is_del' => 0))->find();
                    if (empty($gs_info)) {
                        $arrResultList[] = $item;
                    }
                } else {
                    $arrResultList[] = $item;
                }
            }
        }
        $discount_price = I('discount_price');
        $cash_price = I('cash_price');
        $this->assign('discount_price', $discount_price);
        $this->assign('cash_price', $cash_price);
        $this->assign('list', $arrResultList);
        $this->display();
    }

    public function cate() {
        $where = '1 = 1 ';
        $keywords = I('keywords');
        if ($keywords) {
            $where .= " and ca.cate_name like '%" . $keywords . "%'";
            $this->assign('keywords', $keywords);
        }
        $M = M()->table("ot_goods_category ca")
                ->join('left join ot_shop s on ca.shop_id = s.shop_id');

        $field = 'ca.*,s.shop_name';

        $order = "ca.cate_id desc";
        $list = $this->lists($M, $where, $order, $field);

        if ($list) {
            foreach ($list as &$val) {
                if ($val['shop_id'] == 0) {
                    $val['shop_name'] = '自营';
                }
            }
            unset($val);
        }
        $this->assign('_list', $list);
        $this->display();
    }

    public function addcate() {
        $id = I("id", 0, 'intval');

        if (IS_POST) {
//            $data['icon_url'] = I('icon_url');
            $data['cate_name'] = I("cate_name");

//            if (empty($data['icon_url'])) {
//                $this->error('请选择分类图标或上传图标');
//            }

            if (empty($data['cate_name'])) {
                $this->error('请输入分类名称');
            }

            if ($id == 0) {
                $res = M('GoodsCategory')->add($data);
            } else {
                $res = M('GoodsCategory')->where(array('cate_id' => $id))->save($data);
            }

            if ($res) {
                $this->success('操作成功', U('cate'));
            } else {
                $this->error('操作失败');
            }
        } else {
            $data = M('GoodsCategory')->where(array("cate_id" => $id))->find();
            $this->assign('data', $data);
            $this->display();
        }
    }

    public function setstatus() {
        $id = I("id", 0, 'intval');
        $status = I("s", 0, 'intval');

        $data['status'] = $status;
        $data['update_time'] = date('Y-m-d H:i:s', time());

        $res = M('Goods')->where(array("goods_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    
    public function del() {
        $id = I("id", 0, 'intval');

        $data['update_time'] = date('Y-m-d H:i:s', time());
        $data['is_del'] = 1;

        $res = M('Goods')->where(array("goods_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function attrInfo() {
        $id = I("id", 0, 'intval');
        $keyword = I('keywords');

        $goods_info = M('Goods')->where(array('goods_id' => $id))->find();

        $attr_list = M('GoodsSon')->where(array('goods_id' => $id, 'is_del' => 0))->select();

        $list = array();
        foreach ($attr_list as &$val) {
            $search = '';
            if (!empty($keyword)) {
                $search = M('SpecSon')->where(array('spec_son_name' => array('like', "%$keyword%")))->getField('spec_son_id', true);
            }

            if ($val['spec_group']) {
                $spec_group = explode(',', $val['spec_group']);

                $spec_group = array_filter($spec_group);

                if (!empty($search)) {
                    $intersect = array_intersect($search, $spec_group);

                    if (empty($intersect)) {
                        continue;
                    }
                }


                $where['spec_son_id'] = array('in', $spec_group);
                $son_name = M('SpecSon')->where($where)->getField('spec_son_name', true);
                if (!empty($son_name)) {
                    $val['son_name'] = implode(',', $son_name);
                    $list[] = $val;
                }
            }
        }

        unset($val);

        $this->assign('_list', $list);
        $this->assign('goods', $goods_info);
        $this->display();
    }

    //商品入库
    public function instock() {

        if (IS_POST) {
            $goods_son_id = I('goods_son_id');
            $goods_number = I('goods_number');

            if (empty(array_filter($goods_son_id))) {
                $this->error('没有需要入库的商品');
            }

            if (empty(array_filter($goods_number))) {
                $this->error('请输入入库数量');
            }

            $trans = M();
            $trans->startTrans(); //开启事务
            try {

                $stock_list = [];
                foreach ($goods_son_id as $k => $v) {
                    if ($goods_number[$k] != 0) {
                        $stock_list[] = array('goods_son_id' => $v, 'num' => $goods_number[$k], 'type' => 0);
                        M('GoodsSon')->where(array('goods_son_id' => $v))->setInc('goods_total', $goods_number[$k]);
                    }
                }

                M('StockLog')->addAll($stock_list);
                $trans->commit();
                $this->success('操作成功', U('index'));
            } catch (Exception $ex) {
                $trans->rollback();
                $this->error('操作失败');
            }
        } else {
            $type = I('type');
            if (empty($type)) {
                $this->redirect('barcode', array('type' => 1));
                return;
            }

            $bar_code = I("bar_code", 0, 'intval');

            $goods_info = M('Goods')->where(array('bar_code' => $bar_code))->find();

            if (empty($goods_info)) {
                $this->error('找不到该条码对应的商品');
            }

            $attr_list = M('GoodsSon')->where(array('goods_id' => $goods_info['goods_id'], 'is_del' => 0))->select();

            $list = array();
            foreach ($attr_list as &$val) {
                $spec_group = explode(',', $val['spec_group']);
                $spec_group = array_filter($spec_group);
                $where['spec_son_id'] = array('in', $spec_group);
                $son_name = M('SpecSon')->where($where)->getField('spec_son_name', true);
                if (!empty($son_name)) {
                    $val['son_name'] = implode(',', $son_name);
                    $list[] = $val;
                }
            }

            unset($val);

            $this->assign('_list', $list);
            $this->assign('goods', $goods_info);

            $this->display();
        }
    }

    //商品出库
    public function salegoods() {
        if (IS_POST) {

            $goods_son_id = I('goods_son_id');
            $goods_number = I('goods_number');

            $pay_type = I('pay_type', 1, 'intval');
            $total_price = I('total_price');
            $auth_code = I('auth_code');

            if (empty($total_price)) {
                $this->error('没有需要付款的金额');
            } else {
                $total_price = $total_price * 100;
            }

            if (empty($auth_code) && $pay_type != 0) {
                $this->error('请扫描用户付款码');
            }

            if (empty(array_filter($goods_son_id))) {
                $this->error('没有需要出库的商品');
            }

            if (empty(array_filter($goods_number))) {
                $this->error('请输入出库数量');
            }

            $trans = M();
            $trans->startTrans(); //开启事务
            try {
                $returnMsg = [];

                $stock_list = [];
                foreach ($goods_son_id as $k => $v) {
                    if ($goods_number[$k] > 0) {

                        $stock_num = M('GoodsSon')->where(array('goods_son_id' => $v))->find();

                        if ($stock_num['goods_total'] - $goods_number[$k] < 0) {
                            $total_price -= ($stock_num['discount_price'] * $goods_number[$k]) * 1000;
                            $goodsTitle = M('Goods')->where(array('goods_id' => $stock_num['goods_id']))->getfield('goods_title');
                            $returnMsg[] = $goodsTitle . '的' . $stock_num['spec_group_name'] . '的(' . $goods_number[$k] . ')件商品';
                        } else {
                            $stock_list[] = array('goods_son_id' => $v, 'num' => $goods_number[$k], 'type' => 1, 'pay_type' => $pay_type);
                            M('GoodsSon')->where(array('goods_son_id' => $v))->setDec('goods_total', $goods_number[$k]);
                        }
                    }
                }

                $ret = '';
                //微信支付
                if ($pay_type == 1) {
                    $ret = returnMicroPay($auth_code, $total_price);

                    //appid : wxac1c8e29138286cb 
                    //attach : Array 
                    //bank_type : CFT 
                    //cash_fee : 1 
                    //fee_type : CNY 
                    //is_subscribe : N 
                    //mch_id : 1490439882 
                    //nonce_str : uCiCRjfpIM4rgLEi 
                    //openid : ooNAXxPbNYKhYjPz4nIkCM9U0rcs 
                    //out_trade_no : 149043988220171029202519 
                    //result_code : SUCCESS 
                    //return_code : SUCCESS 
                    //return_msg : OK 
                    //sign : FA3D1A0C6FCE54115C647BD2F8ED3BEC 
                    //time_end : 20171029202520 
                    //total_fee : 1 
                    //trade_state : SUCCESS 
                    //trade_type : MICROPAY 
                    //transaction_id : 4200000028201710291139073354

                    if ($ret['result_code'] != 'SUCCESS') {
                        $this->error('支付错误!' . $ret['err_code_des']);
                        $trans->rollback();
                    }
                }

                //支付宝支付
                if ($pay_type == 2) {
                    $total_price = $total_price / 100;
                    $outTradeNo = '10' . time() . mt_rand(1000, 9999);


//                    array(2) {
//                        ["status"] =>
//                        string(7) "SUCCESS"
//                        ["info"] =>
//                        object(stdClass)#23 (13) {
//                        ["code"] =>
//                        string(5) "10000"
//                        ["msg"] =>
//                        string(7) "Success"
//                        ["buyer_logon_id"] =>
//                        string(11) "137****4628"
//                        ["buyer_pay_amount"] =>
//                        string(4) "0.01"
//                        ["buyer_user_id"] =>
//                        string(16) "2088402528744035"
//                        ["fund_bill_list"] =>
//                        array(1) {
//                            [0] =>
//                            object(stdClass)#24 (2) {
//                            ["amount"] =>
//                            string(4) "0.01"
//                            ["fund_channel"] =>
//                            string(7) "PCREDIT"
//                        }
//                    }
//                    ["gmt_payment"] =>
//                    string(19) "2017-11-09 09:51:51"
//                    ["invoice_amount"] =>
//                    string(4) "0.01"
//                    ["out_trade_no"] =>
//                    string(16) "1015101923091644"
//                    ["point_amount"] =>
//                    string(4) "0.00"
//                    ["receipt_amount"] =>
//                    string(4) "0.01"
//                    ["total_amount"] =>
//                    string(4) "0.01"
//                    ["trade_no"] =>
//                    string(28) "2017110921001004035326674469"
//                }
//                }

                    $ret = barPay($outTradeNo, '国知商品支付', $total_price, $auth_code, '国知商品线下扫码付款');
                    if ($ret['status'] != 'SUCCESS') {
                        $this->error('支付错误!' . $ret['info']);
                        $trans->rollback();
                    }
                }

                foreach ($stock_list as &$val) {
                    $val['wx_json'] = json_encode($ret);
                }
                unset($val);

                M('StockLog')->addAll($stock_list);
                $trans->commit();

                if (empty($returnMsg)) {
                    $this->success('出库成功', U('index'));
                } else {

                    $errmsg['value'] = implode(',', $returnMsg) . ',因库存不足出库失败。';
                    $errmsg['key'] = 'outstockerr';

                    M('Configure')->add($errmsg);
                    $this->error($errmsg['value'], U('outstockerr'), 5);
                }
            } catch (Exception $ex) {
                $trans->rollback();
                $this->error('出库失败');
            }
        } else {
            $type = I('type');
            if (empty($type)) {
                $this->redirect('barcode', array('type' => 2));
                return;
            }

            $bar_code = I("bar_code", 0, 'intval');

            $goods_info = M('Goods')->where(array('bar_code' => $bar_code))->find();
            if (empty($goods_info)) {
                $this->error('找不到该条码对应的商品');
            }

            $attr_list = M('GoodsSon')->where(array('goods_id' => $goods_info['goods_id'], 'is_del' => 0))->select();

            $list = array();
            foreach ($attr_list as &$val) {
                $spec_group = explode(',', $val['spec_group']);
                $spec_group = array_filter($spec_group);
                $where['spec_son_id'] = array('in', $spec_group);
                $son_name = M('SpecSon')->where($where)->getField('spec_son_name', true);
                if (!empty($son_name)) {
                    $val['son_name'] = implode(',', $son_name);
                    $list[] = $val;
                }
            }

            unset($val);

            $this->assign('_list', $list);
            $this->assign('goods', $goods_info);

            $this->display();
        }
    }

    public function barcode() {
        $type = I('type', 1, 'intval');
        if (IS_POST) {
            $bar_code = I('bar_code');
            $goods_info = M('Goods')->where(array('bar_code' => $bar_code))->find();

            if (empty($goods_info)) {
                $this->error('找不到该条码对应的商品');
            }
            if ($type == 1) {
                $this->redirect('instock', array('bar_code' => $bar_code, 'type' => $type));
            }
            if ($type == 2) {
                $this->redirect('salegoods', array('bar_code' => $bar_code, 'type' => $type));
            }
        } else {

            $this->assign('type', $type);
            $this->display();
        }
    }

    public function stocklog() {
        $type = I('type', 0, 'intval');

        $where['type'] = $type;
        $title_name = '入库记录';

        if ($type == 1) {
            $title_name = '出库记录';
        }

        $M = M()->table("ot_stock_log sl")
                ->join('ot_goods_son gs on sl.goods_son_id = gs.goods_son_id')
                ->join('ot_goods g on gs.goods_id = g.goods_id');


        $field = 'sl.*,g.goods_title,g.head_img,gs.spec_group_name';

        $order = "sl.create_time desc";

        $list = $this->lists($M, $where, $order, $field);
        $this->assign('_list', $list);
        $this->assign('type', $type);
        $this->assign('title_name', $title_name);
        $this->display();
    }

    public function payinfo() {
        $id = I('id', 0, 'intval');

        $data = M('StockLog')->where(array("id" => $id))->getField('wx_json');

        $str = "";
        if ($data) {
            foreach (json_decode($data) as $key => $value) {
                $str .= "<font color='#00ff55;'>$key</font> : $value <br/>";
            }
        }


        $this->assign('data', $str);
        $this->display();
    }

    //推荐
    public function recmd() {
        $id = I('id', 0, 'intval');
        $jx = I('jx', 0, 'intval');
        $sort = I('sort', 1, 'intval');


        $data = [];
        if ($jx == 0) {
            $data['is_recmd'] = $sort;
        } else {
            $jx_count = M('Goods')->where(array('is_jx_recmd' => array('neq', '0'), 'status' => array('neq', '0')))->count('goods_id');
            if ($jx_count < 4) {
                $data['is_jx_recmd'] = $sort;
            } else {
                $this->error('精选推荐只能推荐4件商品,请取消其他商品后再推荐');
                return;
            }
        }


        $res = M('Goods')->where(array("goods_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    //取消推荐
    public function cancelrecmd() {
        $id = I('id', 0, 'intval');
        $jx = I('jx', 0, 'intval');


        $data = [];
        if ($jx == 0) {
            $data['is_recmd'] = 0;
        } else {
            $data['is_jx_recmd'] = 0;
        }

        $res = M('Goods')->where(array("goods_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function addAttr() {
        $id = I("id", 0, 'intval');

        if (IS_POST) {
            $goods_son_spec = I('attr');

            if (empty($goods_son_spec)) {
                $this->error('请至少选择一个规格!');
            }


            $goods_son_id = I('goods_son_id');
            $goods_son_price = I('price');
            $goods_son_number = I('goods_num');
            $goods_cash_price = I('cash_price');
            $spec_title_list = I('spec_title');

            $trans = M();
            $trans->startTrans(); //开启事务
            try {
                foreach ($goods_son_spec as $k => $v) {
                    $son['discount_price'] = $goods_son_price[$k];
                    $son['goods_total'] = $goods_son_number[$k];
                    $son['cash_price'] = $goods_cash_price[$k];
                    if (isset($goods_son_id[$k])) {
                        M('GoodsSon')->where(array('goods_son_id' => $goods_son_id[$k]))->save($son);
                    } else {
                        $son['spec_group'] = $v;
                        $son['goods_id'] = $id;
                        $son['spec_group_name'] = $spec_title_list[$k];
                        M('GoodsSon')->add($son);
                    }
                }
                $trans->commit();
                $this->success('添加成功', U('Goods/attrInfo', array('id' => $id)));
            } catch (Exception $ex) {
                $trans->rollback();
                $this->error('操作失败');
            }
        } else {

            $data = M('Goods')->where(array("goods_id" => $id))->find();
            $attr_list = M('GoodsSon')->where(array('goods_id' => $id, 'is_del' => 0))->select();

            $list = array();
            foreach ($attr_list as &$val) {

                if ($val['spec_group']) {
                    $spec_group = explode(',', $val['spec_group']);

                    $spec_group = array_filter($spec_group);


                    $where['spec_son_id'] = array('in', $spec_group);
                    $son_name = M('SpecSon')->where($where)->getField('spec_son_name', true);
                    if (!empty($son_name)) {
                        $val['son_name'] = $son_name;
                        $list[] = $val;
                    }
                }
            }

            unset($val);
//            var_dump($list);die;
            $this->assign('gs_list', $list);
            $this->assign('data', $data);
            $this->specList();
            $this->display();
        }
    }

    //删除子商品
    public function removeGoodsSon() {
        $id = I('id', 0, 'intval');

        $data['is_del'] = 1;
        $res = M('GoodsSon')->where(array("goods_son_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    //首页推荐分类
    public function caterecmd() {
        $id = I('id', 0, 'intval');
        $data['is_recmd'] = I('s', 0, 'intval');

        $recmd_count = M('CateAll')->where(array('is_recmd' => 1))->count('cate_id');
        if ($recmd_count >= 7 && $data['is_recmd'] != 0) {
            $this->error('只能推荐7个分类');
            return;
        }


        $res = M('CateAll')->where(array("cate_id" => $id))->save($data);

        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    //全部商品图标
    public function allgoods() {
        if (IS_POST) {
            $id = I("id", 0, 'intval');
            $g['icon_url'] = I('icon_url');
            $g['cate_name'] = I("cate_name");

            $data['value'] = json_encode($g);
            $data['update_time'] = date('Y-m-d H:i:s', time());
            $data['key'] = 'allgoods';

            if ($id == 0) {
                $res = M('Configure')->add($data);
            } else {
                $res = M('Configure')->where(array('id' => $id))->save($data);
            }


            if ($res) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $data = M('Configure')->where(array("key" => "allgoods"))->find();
            if (!empty($data)) {
                $d = (array) json_decode($data['value']);
                $this->assign('id', $data['id']);
            }

            $this->assign('data', $d);
            $this->display();
        }
    }

    public function goodsalllist() {
        $where .= '1=1 ';
        $goods_id = I('goods_id');
        $goods_title = I('goods_title');
        $goods_id && $where .= "and goods_id = {$goods_id}";
        $goods_title && $where .= "and goods_title like '%" . $goods_title . "%'";

        $M = M()->table("ot_goods g");
        $field = 'g.*';
        $order = "g.goods_id desc";
        $list = $this->lists($M, $where, $order, $field);
        if ($list) {
            foreach ($list as $val) {
                $goods_ids[] = $val['goods_id'];
            }
            $goodsSonList = M('GoodsSon')->field('goods_id,sum(goods_total) as goods_total_sum')
                    ->where(array('goods_id' => ['in', $goods_ids], 'is_del' => 0))
                    ->group('goods_id')
                    ->select();

            foreach ($list as &$val) {
                foreach ($goodsSonList as $vv) {
                    if ($val['goods_id'] == $vv['goods_id']) {
                        $val['goods_total_sum'] = $vv['goods_total_sum'];
                    }
                }
            }
            unset($val);
        }

        $this->assign('_list', $list);
        $this->display();
    }

    public function addsalegoods() {
        $barcode = I('barcode', 0, 'intval');
        if (empty($barcode)) {
            $this->error('请扫描或输入条码');
        }

        $goods_info = M('Goods')->where(array('bar_code' => $barcode))->find();
        if (empty($goods_info)) {
            $this->error('找不到该条码对应的商品');
        }

        $attr_list = M('GoodsSon')->where(array('goods_id' => $goods_info['goods_id'], 'is_del' => 0))->select();

        $list = array();
        foreach ($attr_list as &$val) {
            $spec_group = explode(',', $val['spec_group']);
            $spec_group = array_filter($spec_group);
            $where['spec_son_id'] = array('in', $spec_group);
            $son_name = M('SpecSon')->where($where)->getField('spec_son_name', true);
            if (!empty($son_name)) {
                $val['son_name'] = implode(',', $son_name);
                $list[] = $val;
            }
        }

        unset($val);

        $this->assign('_list', $list);
        $this->assign('goods', $goods_info);

        $this->display();
    }

    public function outstockerr() {
        $M = M()->table("ot_configure g");
        $field = 'g.*';
        $order = "g.create_time desc";
        $where['key'] = 'outstockerr';
        $list = $this->lists($M, $where, $order, $field);
        $this->assign('_list', $list);
        $this->display();
    }

}
